package cn.wonderland.web.controller;

import cn.wonderland.domain.User;
import cn.wonderland.feign.UserFeignClient;
import cn.wonderland.util.DowngradeUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
@RefreshScope // 动态刷新配置注解
public class OrderController {

    @Autowired
    private UserFeignClient userFeignClient;


    @Value("${dynamicRefreshTest}")
    private String dynamicRefreshTest;


    @GetMapping("/{orderId}")
    @SentinelResource(value="user-server-getById",
            blockHandler = "degradationMethod", blockHandlerClass = DowngradeUtil.class
    )
    public String getOrder(@PathVariable("orderId") Long orderId){
        User user = userFeignClient.getUser(orderId);
        return JSONObject.toJSONString(user + dynamicRefreshTest);
    }

    /**
     * 流量控制 服务降级方法
     * @param e 服务降级方法必须接收的异常参数
     */
    public String degradationMethod(Long orderId, BlockException e){
        e.printStackTrace();
        User user = new User(-1L, "流量控制--降级触发！", null, null);
        return JSONObject.toJSONString(user + dynamicRefreshTest);
    }

}
